package com.example.springboot.service;

import com.example.springboot.entity.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.rmi.ServerException;
import java.util.List;

/**
 * 功能
 * 作者：八滴水
 * 日期： 2024/11/19 23:58
 */
@Service
public class UserService {
    @Autowired
    UserMapper userMapper;

    public List<User> selectAll() {
        List<User> users = userMapper.selectAll();
        return users;
    }

    public void insertUser(User user){
        userMapper.insert(user);

    }
    public User selectById(Integer id) {
        System.out.println("Select user with id: " + id);
        return userMapper.selectById(id);
    }

    public User login(User user)  {
        User dbuser = userMapper.selectByName(user.getUsername());
        if(dbuser == null){
           throw new ServiceException("用户名或密码错误");
        }
        if(!dbuser.getPassword().equals(user.getPassword())){
            throw new ServiceException("用户名或密码错误");

        }
        String token = TokenUtils.creatToken(dbuser.getId().toString(),dbuser.getPassword());
        dbuser.setToken(token);
        return dbuser;
    }

    public User register(User user) {
        User dbuser = userMapper.selectByName(user.getUsername());
        if(dbuser != null){
            throw new ServiceException("该用户名已存在");
        }
        userMapper.insert(user);
        return userMapper.selectByName(user.getUsername());
    }
    public void  update(User user){
        userMapper.update(user);
    }

}



